package sketch.shape.domain;

import java.awt.Color;
import java.awt.Graphics2D;
import java.util.ArrayList;
import java.util.List;

import sketch.shape.Shape;
import sketch.shape.ShapeOption;
import sketch.shape.arrow.ArrowHead;
import sketch.shape.geom.prim.Line;
import sketch.shape.geom.prim.Point;

public class LinkEnd extends Shape implements DomainShape {

	public static enum TYPE {
		PLAIN,
		OPENARROW,
		TRIANGLEARROW,
		DIAMONDARROW
	};

	private int endShapeId;

	private TYPE type;

	private List<Line> path;

	private Shape end;

	public LinkEnd() {
		path = new ArrayList<Line>();
		type = TYPE.PLAIN;
	}

	public void setEnd(Shape newEnd) {
		end = newEnd;
	}

	public Shape getEnd() {
		return end;
	}

	public Point getEndPoint() {
		if (getType() == TYPE.PLAIN) {
			Line line = (Line) getEnd();
			return (line.getP1().distance(getEndShape().getCenter()) <
					line.getP2().distance(getEndShape().getCenter()))
					?
					line.getP1() : line.getP2();
		} else {
			return ((ArrowHead)getEnd()).getHead();
		}
	}

	public int getEndShapeId() {
		return endShapeId;
	}

	public void setEndShapeId(int shapeId) {
		this.endShapeId = shapeId;
	}

	public Shape getEndShape() {
		if (getHost() != null)
			return getHost().getShapeById(getEndShapeId());
		return null;
	}

	public void setEndShape(Shape shape) {
		setEndShapeId(shape.getId());
	}

	public TYPE getType() {
		return type;
	}

	public void setType(TYPE type) {
		this.type = type;
	}

	public void setType(String name) {
		if (name.equals("OpenArrowHead")) {
			setType(TYPE.OPENARROW);
		} else if (name.equals("TriangleArrowHead")) {
			setType(TYPE.TRIANGLEARROW);
		} else if (name.equals("DiamondArrowHead")) {
			setType(TYPE.DIAMONDARROW);
		} else {
			setType(TYPE.PLAIN);
		}
	}

	public List<Line> getPath() {
		return path;
	}

	public void setPath(List<Line> newPath) {
		path = newPath;
	}

	public void append(Line line) {
		getPath().add(line);
	}

	public void drawComponent(Graphics2D g2) {
		super.drawComponent(g2);

		for (Line line : path) {
			line.drawComponent(g2);
		}

		getEnd().drawComponent(g2);
	}

	public void drawSelected(Graphics2D g2) {
//		super.drawSelected(g2);

//		getEndShape().drawSelected(g2);
		drawWith(g2, ShapeOption.selectionColor, ShapeOption.selectionWidth);
	}

	public String getShapeSemantics() {
		return "LinkEnd - " + getType().toString();
	}

	public java.awt.Shape getBound(double GAP) {
		java.awt.Shape shape = null;
		for (Line line : path) {
			if (shape == null)
				shape = line.getBound(GAP);
			else
				shape = shape.getBounds().union(line.getBound(GAP).getBounds());
		}
		return shape;
	}

	public String[][] getFieldValues() {
		return new String[][] {
				{"Type", getType().toString()},
				{"EndShapeId", Integer.toString(getEndShapeId())}
		};
	}



}
